﻿using Domain.Entitys.DB;
using Domain.IRepositorys.DB;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EFCore.Repositorys.DB
{
    /// <summary>
    /// 库区(Efcore)
    /// </summary>
    public class Db_warehouseZoneRepositpry : DB_warehouse_zone
    {
        private readonly MyDbContext myDbContext;

         public Db_warehouseZoneRepositpry(MyDbContext myDbContext)
         {
             this.myDbContext = myDbContext;
         }



        /// <summary>
        /// 查询总数量
        /// </summary>
        /// <param name="warehouse_code"></param>
        /// <param name="zone_name"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public int Select_count_warehouse_zone(string warehouse_code, string zone_name)
        {
            //条件筛选
           IQueryable<Warehouse_zone> query=myDbContext.db_warehouse_zone.Where(e => e.Del_flag == '0' && e.warehouse_code == warehouse_code);
            if (!string.IsNullOrEmpty(zone_name)) { 
            query=query.Where(e => e.zone_name.Contains(zone_name));
            }
            //返回总数量
            return query.Count();
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="warehouse_code"></param>
        /// <param name="zone_name"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<Warehouse_zone> Select_fy_warehouse_zone(string warehouse_code, string zone_name, int currentPage, int pageSize)
        {
            //创建逻辑状态为0的查询
            IQueryable<Warehouse_zone> query = myDbContext.db_warehouse_zone.Where(e => e.Del_flag == '0'&& e.warehouse_code == warehouse_code);
            if (!string.IsNullOrEmpty(zone_name)) { 
            query=query.Where(e => e.zone_name.Contains(zone_name));   
            }
            //添加分页
            var pages = query.Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();

            return pages;
        }
        /// <summary>
        /// 仓库库区添加
        /// </summary>
        /// <param name="warehouse_zone"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Warehousezone_Add(Warehouse_zone warehouse_zone)
        {
          await myDbContext.db_warehouse_zone.AddAsync(warehouse_zone);
            return await myDbContext.SaveChangesAsync();    
        }



        /// <summary>
        /// 仓库库区编码唯一性判断
        /// </summary>
        /// <param name="zone_code"></param>
        /// <param name="warehouse_code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Warehousezone_code_judgment(string zone_code, string warehouse_code)
        {
            return await myDbContext.db_warehouse_zone.Where(e => e.Del_flag == '0' && e.warehouse_code == warehouse_code && e.zone_code == zone_code).CountAsync();
        }
        /// <summary>
        /// 仓库库区名称唯一性判断
        /// </summary>
        /// <param name="zone_name"></param>
        /// <param name="warehouse_code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<int> Warehousezone_name_judgment(string zone_name, string warehouse_code)
        {
           return myDbContext.db_warehouse_zone.Where(e => e.Del_flag == '0' && e.warehouse_code == warehouse_code && e.zone_name == zone_name).CountAsync();
        }

   
        /// <summary>
        /// 修改库区冻结状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="zone_freeze"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> warehouse__zone_Frozenstate(int id, char zone_freeze)
        {
            Warehouse_zone warehouse_Zone = await myDbContext.db_warehouse_zone.FindAsync(id);

            if (warehouse_Zone == null)
            {
                return 0;
            }
            if (warehouse_Zone.Del_flag != '0')
            {
                
                return 0; 
            }


            if (zone_freeze == '0')
            {
                warehouse_Zone.zone_freeze = '1';
            }
            else
            {
                warehouse_Zone.zone_freeze = '0';
            }
            return await myDbContext.SaveChangesAsync();
        }



        /// <summary>
        /// 库区是否允许产品混放
        /// </summary>
        /// <param name="id"></param>
        /// <param name="zone_mixing"></param>
        /// <returns></returns>
        public async Task<int> Warehousezone_ProductMix(Warehouse_zone warehouse_zone)
        {
            var warehouseZone = await myDbContext.db_warehouse_zone
       .FindAsync(warehouse_zone.zone_id);

            if (warehouseZone == null)
            {
                Console.WriteLine("找不到对应的库区");
                return 0;
            }

            warehouseZone.zone_mixing = warehouse_zone.zone_mixing;



            var locations = await myDbContext.db_warehouse_location
                .Where(e => e.Del_flag == '0' && e.zone_code == warehouseZone.zone_code)
                .ToListAsync();

            foreach (var location in locations)
            {
                location.location_allow_mix = warehouseZone.zone_mixing;
            }


            try
            {
                int rowsAffected = await myDbContext.SaveChangesAsync();
                return rowsAffected; // 0 表示无更改，>0 表示有更新
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("保存更改失败: " + ex.Message);
                return -2; // 表示发生异常
            }
        }


        /// <summary>
        /// 库区是否不允许产品混放
        /// </summary>
        /// <param name="id"></param>
        /// <param name="zone_mixing"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Warehousezone_ProductMixNO(Warehouse_zone warehouse_zone)
        {
            var Swer = await myDbContext.db_warehouse_zone.FindAsync(warehouse_zone.zone_id);
            if (Swer == null)
            {
                Console.WriteLine("找不到对应的库区");
                return 0;
            }
            Swer.zone_mixing = warehouse_zone.zone_mixing;

            var locations = await myDbContext.db_warehouse_location.Where(e => e.Del_flag == '0' && e.zone_code == Swer.zone_code).ToListAsync();

            foreach (var location in locations) {

                location.location_allow_mix = warehouse_zone.zone_mixing;
            }

            try
            {
                int rowsAffected = await myDbContext.SaveChangesAsync();
                return rowsAffected; // 0 表示无更改，>0 表示有更新
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("保存更改失败: " + ex.Message);
                return -2; // 表示发生异常
            }
        }

        /// <summary>
        ///  库区否允许批次混放
        /// </summary>
        /// <param name="id"></param>
        /// <param name="zone_batch_mixing"></param>
        /// <returns></returns>
        public async  Task<int> Warehousezone_BatchMix(Warehouse_zone warehouse_zone)
        {
            var Swer = await myDbContext.db_warehouse_zone.FindAsync(warehouse_zone.zone_id);
            if (Swer == null)
            {
                Console.WriteLine("找不到对应的库区");
                return 0;
            }
            Swer.zone_batch_mixing = warehouse_zone.zone_batch_mixing;

            var locations = await myDbContext.db_warehouse_location.Where(e => e.Del_flag == '0' && e.zone_code == Swer.zone_code).ToListAsync();

            foreach (var location in locations)
            {

                location.location_batch_mix = warehouse_zone.zone_batch_mixing;
            }

            try
            {
                int rowsAffected = await myDbContext.SaveChangesAsync();
                return rowsAffected; // 0 表示无更改，>0 表示有更新
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("保存更改失败: " + ex.Message);
                return -2; // 表示发生异常
            }
        }
        /// <summary>
        /// 库区否不允许批次混放
        /// </summary>
        /// <param name="id"></param>
        /// <param name="zone_batch_mixing"></param>
        /// <returns></returns>
        public async Task<int> Warehousezone_BatchMixNO(Warehouse_zone warehouse_zone)
        {
             var Swer = await myDbContext.db_warehouse_zone.FindAsync(warehouse_zone.zone_id);
            if (Swer == null)
            {
                Console.WriteLine("找不到对应的库区");
                return 0;
            }
            Swer.zone_batch_mixing = warehouse_zone.zone_batch_mixing;

            var locations = await myDbContext.db_warehouse_location.Where(e => e.Del_flag == '0' && e.zone_code == Swer.zone_code).ToListAsync();

            foreach (var location in locations)
            {

                location.location_batch_mix = warehouse_zone.zone_batch_mixing;
            }

            try
            {
                int rowsAffected = await myDbContext.SaveChangesAsync();
                return rowsAffected; // 0 表示无更改，>0 表示有更新
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("保存更改失败: " + ex.Message);
                return -2; // 表示发生异常
            }
        }

        /// <summary>
        /// 判断添加的时候库区的容量是否超过最大容量
        /// </summary>
        /// <param name="warehouse_code"></param>
        /// <param name="zone_capacity"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Warehousezone_Capacity_judgment(string warehouse_code, int zone_capacity)
        {
            var fq = await myDbContext.db_warehouse.Where(e => e.Warehouse_code == warehouse_code && e.Del_flag == '0').FirstOrDefaultAsync();

            if (fq == null)
            {
                // 仓库不存在或已被删除
                return -1;
            }

            var Warehousezonesjk=await myDbContext.db_warehouse_zone.Where(e => e.warehouse_code == warehouse_code && e.Del_flag == '0').ToListAsync();
            //获取仓库最大容量
            int zongcapacity = fq.Warehouse_capacity;
            //计算仓库库区所有库区已使用容量
            int totalUsedCapacity = Warehousezonesjk.Sum(e => e.zone_capacity);

            //添加添加的容量
            int futureTotalCapacity=totalUsedCapacity+zone_capacity;


            // 判断是否超过仓库最大容量
            if (futureTotalCapacity > zongcapacity)
            {
                // 超出容量，不允许添加
                return 0;
            }
            else
            {
                // 容量足够，允许添加
                return 1;
            }
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="warehouse_zone"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Warehousezone_Update(Warehouse_zone warehouse_zone)
        {
            var weahouse_zone_update = await myDbContext.db_warehouse_zone.FirstOrDefaultAsync(w => w.zone_code == warehouse_zone.zone_code);

            if (weahouse_zone_update == null) { 
            return 0;
            }

            weahouse_zone_update.zone_name=warehouse_zone.zone_name;
            weahouse_zone_update.zone_capacity=warehouse_zone.zone_capacity;
            weahouse_zone_update.zone_available=warehouse_zone.zone_available;
            weahouse_zone_update.remarks=warehouse_zone.remarks;
            weahouse_zone_update.Update_by=warehouse_zone.Update_by;
            weahouse_zone_update.Update_time=warehouse_zone.Update_time;
            weahouse_zone_update.Del_flag=warehouse_zone.Del_flag;

            return await myDbContext.SaveChangesAsync();
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="warehouse_code"></param>
        /// <param name="zone_code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> warehouse_zone_tombstone(string warehouse_code, string zone_code)
        {
            // 1. 检查库存
            var hasStock = await myDbContext.inv_stock
                .AnyAsync(s => s.Warehouse_Code == warehouse_code
                            && s.Zone_Code == zone_code
                            && s.Del_Flag == '0'
                            && s.stock_numder > 0);
            if (hasStock) return 0;

            // 2. 检查库位
            var hasLocation = await myDbContext.db_warehouse_location
                .AnyAsync(l => l.zone_code == zone_code
                            && l.Del_flag == '0');
            if (hasLocation) return 0;

            // 3. 逻辑删除库区
            var zone = await myDbContext.db_warehouse_zone
                .FirstOrDefaultAsync(z => z.warehouse_code == warehouse_code
                                       && z.zone_code == zone_code
                                       && z.Del_flag == '0');
            if (zone == null) throw new Exception("库区不存在");

            zone.Del_flag = '1';
         
            return await myDbContext.SaveChangesAsync();
        }

        /// <summary>
        /// 仓库库区
        /// </summary>
        /// <param name="warehouse_code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<Warehouse_zone> warehouse_zone_Async(string warehouse_code)
        {
            var warehouse_zon = myDbContext.db_warehouse_zone.Where(e => e.Del_flag == '0' && e.warehouse_code == warehouse_code).ToList();
            return warehouse_zon;
        }





        public List<Warehouse_zone> Warehouse_zone_By_Select_Async_code(string warehouse_code, string zone_code)
        {
            var weahouse = myDbContext.db_warehouse_zone.Where(e => e.Del_flag == '0' && e.warehouse_code == warehouse_code && e.zone_code == zone_code).ToList();
            return weahouse;
        }
        /// <summary>
        /// 判断仓库库区修改的容量是否超过仓库容量
        /// </summary>
        /// <param name="warehouse_code"></param>
        /// <param name="zone_code"></param>
        /// <param name="new_zone_capacity"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Warehousezone_Capacity_judgment_update(string warehouse_code, string zone_code, int new_zone_capacity)
        {
            // 1. 仓库信息
            var warehouse = await myDbContext.db_warehouse
                .Where(e => e.Warehouse_code == warehouse_code && e.Del_flag == '0')
                .FirstOrDefaultAsync();

            if (warehouse == null)
                return -1;                       // 仓库不存在

            int warehouseMaxCap = warehouse.Warehouse_capacity;

            // 2. 该仓库下所有未删除的库区（包含待修改这条）
            var zones = await myDbContext.db_warehouse_zone
                .Where(e => e.warehouse_code == warehouse_code && e.Del_flag == '0')
                .ToListAsync();

            // 3. 当前要修改的库区
            var targetZone = zones.FirstOrDefault(e => e.zone_code == zone_code); // 假设主键字段叫 Zone_id
            if (targetZone == null)
                return -1;                      // 库区不存在（也可自定义返回码）

            int oldZoneCap = targetZone.zone_capacity;

            // 4. 计算修改后的仓库已用总容量
            int otherZonesTotalCap = zones
                .Where(e => e.zone_code != zone_code)
                .Sum(e => e.zone_capacity);

            int futureTotalUsed = otherZonesTotalCap + new_zone_capacity;

            // 5. 判断是否超限
            return futureTotalUsed <= warehouseMaxCap ? 1 : 0;
        }
        /// <summary>
        /// 修改库区名称时的唯一性判断
        /// </summary>
        /// <param name="zone_name"></param>
        /// <param name="warehouse_code"></param>
        /// <param name="zone_code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<int> Warehousezone_name_UpdateJudgment(string zone_name, string warehouse_code, string zone_code)
        {
            return myDbContext.db_warehouse_zone
       .Where(e => e.Del_flag == '0'
                   && e.warehouse_code == warehouse_code
                   && e.zone_name == zone_name
                   && e.zone_code != zone_code)   // 排除自己
       .CountAsync();
        }
    }
}
